<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        formItemWidth="120px"
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :remoteMethod="getProductNameByRemote"
        :optionDisabledMethod="isOptionDisabled"
        :selectRemoteLoading="selectRemoteLoading"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <BasicTable
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="480"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
        @handleSortChange="handleSortChange"
      />
    </el-card>
  </div>
</template>
<script>
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { requestToData } from '@/api/commonHttp';
import { formItemList, tableColumns } from './constants';
export default {
  components: {
    BasicForm,
    BasicTable,
  },
  data () {
    return {
      formItemList: formItemList,
      formData: {
        recordCommitType: [], // 变更类型
        recordOpeTime: '', // 变更时间
        archivalDataSearch: '2', // 归档数据查询
        supplyUuid: '', // 供应商编码
        skuNo: '', // SKU编码
        spuNo: [], // SPU编码（商品名称label项）
        saleProvinceName: '', // 销售省
      },
      tableInfo: {
        list: [],
        columns: tableColumns,
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 100, 1000],
      selectRemoteLoading: false
    }
  },
  mounted () {
    // this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.handleQueryForm();
    },
    // 是归档数据查询
    isArchivalDataSearch () {
      return this.formData.archivalDataSearch === '1';
    },
    // sku编码或商品名称(实际是spuNo)为空
    isEmptyForSkuNoOrProductName () {
      const { skuNo, spuNo } = this.formData;
      return !skuNo && (!spuNo || spuNo.length === 0);
    },
    // 当前值为空
    hasNoVal (val) {
      if (Array.isArray(val)) { return val.length === 0; }
      return !val;
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 获取查询入参conditions的item
    getItemByConditions (propertyName, matchType = 'LIKE', value) {
      if (this.hasNoVal(value)) { return undefined; }
      if (Array.isArray(value)) { return { propertyName, matchType, value: value.join(',') } }
      return { propertyName, matchType, value }
    },
    // 获取查询入参
    getParamsBySearch (orders) {
      const noNeedCheckItems = ['recordOpeTime', 'archivalDataSearch'];
      const conditions = formItemList
        .filter(item => !noNeedCheckItems.includes(item.prop))
        .map(item => (this.getItemByConditions(
          item.prop, item.matchType, this.formData[item.prop]
        )));
      const { recordOpeTime } = this.formData;
      const [startTime, endTime] = recordOpeTime || [];
      conditions.push(this.getItemByConditions('recordOpeTime', 'GE', startTime));
      conditions.push(this.getItemByConditions('recordOpeTime', 'LE', endTime));
      const { nowPage, pageShow } = this.pagination;
      return {
        conditions: conditions.filter(item => item),
        pageNum: nowPage,
        pageSize: pageShow,
        orders: orders || [{ propertyName: 'recordOpeTime', orderType: 'desc' }]
      }
    },
    // 获取表格数据 by 查询表单
    async getTableDataBySearchForm (orders) {
      if (this.isEmptyForSkuNoOrProductName()) {
        return this.$message.warning('SKU编码或商品名称不能为空');
      }
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const listUrl = '/dataBatch/product/supply/price/getChangeLogList'; // 普通查询接口
      const historyListUrl = '/dataBatch/product/supply/price/getChangeLogHistoryList'; // 历史查询接口
      const retData = await requestToData({
        url: this.isArchivalDataSearch() ? historyListUrl : listUrl,
        type: 'post',
        data: this.getParamsBySearch(orders)
      }, () => { this.tableInfo.loading = true },
      () => { this.tableInfo.loading = false });
      if (retData) {
        this.tableInfo.list = retData?.results || [];
        this.pagination.totalNum = retData?.totalNum || 0;
      }
    },
    // 表单下拉框禁用方法
    isOptionDisabled ({ option, item }) {
      if (item.prop !== 'spuNo') { return false; }
      if (this.formData.spuNo.includes(option.value)) { return false; }
      return this.formData.spuNo.length >= 20;
    },
    // 表单下拉远程请求获取商品名称集合
    async getProductNameByRemote (productName) {
      if (!productName) { return null; }
      const retData = await requestToData({
        url: '/sysback/finish/spu/mgr/getProductMainSimpleVosByProductName',
        type: 'post',
        data: { productName },
        isFormData: true
      }, () => { this.selectRemoteLoading = true; }, () => { this.selectRemoteLoading = false; });
      return retData.map(item => ({
        label: `${item.productNameFinal} (${item.spuNo})`,
        value: item.spuNo
      }));
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableDataBySearchForm();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataBySearchForm();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataBySearchForm();
    },
    // 表格排序
    handleSortChange ({ prop, order }) {
      const orders = [{
        propertyName: prop,
        orderType: order === 'ascending' ? 'asc' : 'desc' // 只有排序为ascending的时候给asc，其余descending和null都默认为desc
      }];
      this.getTableDataBySearchForm(orders);
    },
  }
}
</script>
